package com.ebelter.ty.ui.fragment.scale;


import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;

import com.ebelter.btcomlib.bases.fragment.BaseFragment;
import com.ebelter.btcomlib.common.Constants;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.StringUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;

import com.ebelter.ty.AppConfig;
import com.ebelter.ty.R;
import com.ebelter.ty.adapters.TrendHLvAdapter;
import com.ebelter.ty.model.http.TyNetUtil;
import com.ebelter.ty.model.http.bean.GetAverageResponse;
import com.ebelter.ty.ui.views.CombinView1;
import com.ebelter.ty.ui.views.EndlessRecyclerOnScrollListener;
import com.ebelter.ty.ui.views.HoriLineView;
import com.ebelter.ty.utils.ScaleBaseUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;


/**
 * 血糖
 */

public class Scale_M_B4_Fragment extends BaseFragment implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {


    public static final String TAG = "Scale_M_B4_Fragment";



    private ImageView gn_rg_weight;//体重
    private ImageView gn_rg_fat;//脂肪
    private ImageView gn_rg_muscle;//肌肉
    private ImageView gn_rg_heart;//心率

    private int current_GongNeng_rg_index=0; //0体重1脂肪2肌肉3心率
    private int current_Time_rg_index=10; //10天11周12月


    private RadioGroup trend_time_rg;

    private RecyclerView trend_hlv;
    private HoriLineView horlineview;
    private TrendHLvAdapter trendHLvAdapter;

    CombinView1 trend_avg_weight_cb1;
    CombinView1 trend_change_weight_cb1;



    private String avg_weight_day;
    private String avg_weight_week;
    private String avg_weight_month;
    private String avg_bfp_day;
    private String avg_bfp_week;
    private String avg_bfp_month;
    private String avg_mass_day;
    private String avg_mass_week;
    private String avg_mass_month;
    private String change_weight;
    private String change_bodyfat_percentage;
    private String change_muscle_mass;

    private String unitKg = StringUtils.getResStr(R.string.kg);
    private String unitLb = StringUtils.getResStr(R.string.lb);
    private void getStrs(){
        avg_weight_day=StringUtils.getResStr(R.string.avg_weight_day);
        avg_weight_week=StringUtils.getResStr(R.string.avg_weight_week);
        avg_weight_month=StringUtils.getResStr(R.string.avg_weight_month);
        avg_bfp_day=StringUtils.getResStr(R.string.avg_bfp_day);
        avg_bfp_week=StringUtils.getResStr(R.string.avg_bfp_week);
        avg_bfp_month=StringUtils.getResStr(R.string.avg_bfp_month);
        avg_mass_day=StringUtils.getResStr(R.string.avg_mass_day);
        avg_mass_week=StringUtils.getResStr(R.string.avg_mass_week);
        avg_mass_month=StringUtils.getResStr(R.string.avg_mass_month);
        change_weight=StringUtils.getResStr(R.string.change_weight);
        change_bodyfat_percentage=StringUtils.getResStr(R.string.change_bodyfat_percentage);
        change_muscle_mass=StringUtils.getResStr(R.string.change_muscle_mass);
    }


    @Override
    protected int setLayoutResouceId() {
        return R.layout.scale_m_buttom4_trend;
    }

    @Override
    protected void initView() {
        super.initView();

        FV();
    }

    @Override
    protected void initData(Bundle arguments) {
        super.initData(arguments);
        getStrs();
        initCharView();
        gnGrSelect(current_GongNeng_rg_index);
        timeGrSelect(current_Time_rg_index);


    }

    private void initCharView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        trend_hlv.setLayoutManager(linearLayoutManager);
        trendHLvAdapter=new TrendHLvAdapter(getActivity());
        trend_hlv.setAdapter(trendHLvAdapter);

        // 设置加载更多监听
        trend_hlv.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore(boolean isSlidingToLeft) {
                // 加载更多
                LogUtils.e(TAG,"-----onLoadMore() isSlidingToLeft="+isSlidingToLeft);
                if (!isSlidingToLeft){
                    requestDisplayData(false,false);
                }
            }
        });
    }

    private void timeGrSelect(int current_time_rg_index) {
        if (current_time_rg_index==10){
            trend_time_rg.check(R.id.trg_day);
        }else if (current_time_rg_index==11){
            trend_time_rg.check(R.id.trg_week);
        }else if (current_time_rg_index==12){
            trend_time_rg.check(R.id.trg_month);
        }
    }

    private void FV() {
        gn_rg_weight = mRootView.findViewById(R.id.gn_rg_weight);
        gn_rg_fat = mRootView.findViewById(R.id.gn_rg_fat);
        gn_rg_muscle = mRootView.findViewById(R.id.gn_rg_muscle);
        gn_rg_heart = mRootView.findViewById(R.id.gn_rg_heart);
        trend_time_rg = mRootView.findViewById(R.id.trend_time_rg);
        trend_hlv = mRootView.findViewById(R.id.trend_hlv);
        horlineview = mRootView.findViewById(R.id.horlineview);

        trend_avg_weight_cb1 = mRootView.findViewById(R.id.trend_avg_weight_cb1);
        trend_change_weight_cb1 = mRootView.findViewById(R.id.trend_change_weight_cb1);

        gn_rg_weight.setOnClickListener(this);
        gn_rg_fat.setOnClickListener(this);
        gn_rg_muscle.setOnClickListener(this);
        gn_rg_heart.setOnClickListener(this);
        trend_time_rg.setOnCheckedChangeListener(this);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.gn_rg_weight:
                gnGrSelect(0);
                break;
            case R.id.gn_rg_fat:
                gnGrSelect(1);
                break;
            case R.id.gn_rg_muscle:
                gnGrSelect(2);
                break;
            case R.id.gn_rg_heart:
                gnGrSelect(3);
                break;

        }
    }


    private void gnGrSelect(int index){
        current_GongNeng_rg_index = index;
        ViewUtils.setSelects(false,gn_rg_weight,gn_rg_fat,gn_rg_muscle,gn_rg_heart);
        if (current_GongNeng_rg_index==0){
            ViewUtils.setSelect(gn_rg_weight,true);
        }else if (current_GongNeng_rg_index==1){
            ViewUtils.setSelect(gn_rg_fat,true);
        }else if (current_GongNeng_rg_index==2){
            ViewUtils.setSelect(gn_rg_muscle,true);
        }else if (current_GongNeng_rg_index==3){
            ViewUtils.setSelect(gn_rg_heart,true);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.trg_day:
                LogUtils.i(TAG,"gr_时间_天");
                break;
            case R.id.trg_week:
                LogUtils.i(TAG,"gr_时间_周");
                break;
            case R.id.trg_month:
                LogUtils.i(TAG,"gr_时间_月");
                break;
        }
    }

    private long lastLoadMoreTime;
    private boolean isLoadingData;
    private int DAY_START_INDEX;
    private int WEEK_START_INDEX;
    private int MONTH_START_INDEX;

    public void requestDisplayData(final boolean scroll2end,boolean isFrom0) {

        lastLoadMoreTime=System.currentTimeMillis();
        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
            return;
        }
        if (isLoadingData){
            LogUtils.i(TAG,"正在加载数据，此次请求拒绝掉");
            return;
        }



        if (isFrom0){

            DAY_START_INDEX=0;

            WEEK_START_INDEX=0;

            MONTH_START_INDEX=0;

            if (trendHLvAdapter!=null){
                trendHLvAdapter.clearData();
            }

        }

        LogUtils.i(TAG, "-------requestDisplayData()------current_Time_rg_index = "+current_Time_rg_index+"-------current_GongNeng_rg_index = "+current_GongNeng_rg_index);
        final int whichTime;
        final int start_index;
        if (current_Time_rg_index==10){
            whichTime=10;
            start_index=DAY_START_INDEX;
        }else if (current_Time_rg_index==11){
            whichTime=11;
            start_index=WEEK_START_INDEX;
        }else if (current_Time_rg_index==12){
            whichTime=12;
            start_index=MONTH_START_INDEX;
        }else {
            return;
        }
        isLoadingData=true;

        LogUtils.i(TAG, "-------whichTime = "+whichTime+"-------current_GongNeng_rg_index = "+current_GongNeng_rg_index);
        Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put("userId", UserSpUtil.readLong(Constants.IUser.USER_ID));
        paramMap.put("startIndex", start_index);
        // paramMap.put(HttpsParameters.PAGE_SIZE, AppDateLitConstants.PAGE_SIZE);
        paramMap.put("pageSize", 100);

        TyNetUtil.getInstance().getsAverageData(this, whichTime, paramMap, new HttpResponse<GetAverageResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, GetAverageResponse getAverageResponse,String s) {
                LogUtils.i(TAG,"---------------start_index="+start_index);
                //  SystemClock.sleep(3000);
                if (isRequestSuccess){
                    if (getAverageResponse.resultCode==0){
                        LogUtils.i(TAG,"---------------getsAverageData请求成功--------------"+getAverageResponse);
                        if (getAverageResponse.getResultData()!=null&&getAverageResponse.getResultData().getData()!=null&&getAverageResponse.getResultData().getData().size()>0){
                            LogUtils.i(TAG,"---------------getsAverageData请求成功--------------whichTime="+whichTime+"--" +
                                    "-DAY_START_INDEX="+DAY_START_INDEX+"----WEEK_START_INDEX="+WEEK_START_INDEX+"----MONTH_START_INDEX="+MONTH_START_INDEX);
                            if (getAverageResponse.getResultData()!=null&&getAverageResponse.getResultData().getData()!=null&&getAverageResponse.getResultData().getData().size()>0){
                                if (whichTime==10){
                                    DAY_START_INDEX++;
                                }else if (whichTime==11){
                                    WEEK_START_INDEX++;
                                }else if (whichTime==12){
                                    MONTH_START_INDEX++;
                                }
                            }

                            displayData(getAverageResponse.getResultData(),whichTime,scroll2end);
                        }

                    }else {
                        LogUtils.i(TAG,"---------------getsAverageData请求失败-------原因-----"+getAverageResponse.resultMessage);
                    }
                }else {
                    LogUtils.i(TAG,"---------------getsAverageData请求失败--------------");
                }
                isLoadingData=false;
            }
        });


    }


    //显示数据 whichTime 1DAY 2WEEK 3MONTH
    private void displayData(final GetAverageResponse.ResultDataBean resultData,int whichTime,final boolean scroll2end) {
        LogUtils.i(TAG,"---displayData---A--whichTime="+whichTime);
        if (resultData==null){
            return;
        }
        if (trendHLvAdapter!=null){
            trendHLvAdapter.addDatas(resultData.getData(),whichTime);
            if (scroll2end){
                ViewUtils.recyclerViewScrollToPosition(trend_hlv,trendHLvAdapter.getItemCount()-1);
            }
            displayTargetWeightLine();
            updateCb1Title1();
        }
    }

    //显示目标体重横线
    public void displayTargetWeightLine(){
        LogUtils.i(TAG,"---displayTargetWeightLine---A");
        if (horlineview==null){
            return;
        }
        LogUtils.i(TAG,"---displayTargetWeightLine---B");
        if (trendHLvAdapter!=null&&trendHLvAdapter.getItemCount()!=0){
            LogUtils.i(TAG,"---displayTargetWeightLine---C");
            horlineview.setDisplay(true);
            float p=0;
            String displayText="";
            trendHLvAdapter.calculator();//计算一遍的意思
            if (trendHLvAdapter.maxWeight<=0){
                p=0;
            }else {
                float targetWeight=UserSpUtil.readFloat(Constants.IUser.TARGET_WEIGHT);
                p= targetWeight/trendHLvAdapter.maxWeight;
                displayText= NumUtils.numBaoLiuWei1(ScaleBaseUtils.adapterDataFloat(targetWeight))+"";
            }
            LogUtils.i(TAG,"---displayTargetWeightLine---D--p="+p+"---displayText="+displayText);
            horlineview.setPercentage(p);
            if (p==0){
                horlineview.setDisplay(false);
            }
            horlineview.setDisplayText(displayText);
        }else {
            horlineview.setDisplay(false);
        }
        horlineview.show();
    }

    //更新title1
    private void updateCb1Title1() {
        String title11="";
        String title21="";
        String title12="";
        String title22="";
        String title13="";

        if (current_GongNeng_rg_index==10){
            switch (current_GongNeng_rg_index){
                case 0:
                    title11=avg_weight_day;
                    title21=change_weight;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1(ScaleBaseUtils.adapterDataFloat(trendHLvAdapter.getAvg(10,0)))+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1(trendHLvAdapter.getChange(10,0))+"":"";
                    title13= AppConfig.getInstance().isKgModel()?unitKg:unitLb;;
                    break;
                case 1:
                    title11=avg_bfp_day;
                    title21=change_bodyfat_percentage;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1( trendHLvAdapter.getAvg(10,1))+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1(trendHLvAdapter.getChange(10,1))+"":"";
                    title13="%";
                    break;
                case 2:
                    title11=avg_mass_day;
                    title21= StringUtils.getResStr(R.string.change_muscle_mass);
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1(ScaleBaseUtils.adapterDataFloat(trendHLvAdapter.getAvg(10,2)))+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1(trendHLvAdapter.getChange(10,2))+"":"";
                    title13=AppConfig.getInstance().isKgModel()?unitKg:unitLb;
                    break;
            }

        }else if (current_GongNeng_rg_index==11){
            switch (current_GongNeng_rg_index){
                case 0:
                    title11=avg_weight_week;
                    title21=change_weight;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1(ScaleBaseUtils.adapterDataFloat(trendHLvAdapter.getAvg(11,0)))+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1(trendHLvAdapter.getChange(11,0))+"":"";
                    title13=AppConfig.getInstance().isKgModel()?unitKg:unitLb;
                    break;
                case 1:
                    title11=avg_bfp_week;
                    title21=change_bodyfat_percentage;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1(trendHLvAdapter.getAvg(11,1))+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1( trendHLvAdapter.getChange(11,1))+"":"";
                    title13="%";
                    break;
                case 2:
                    title11=avg_mass_week;
                    title21=change_muscle_mass;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1(ScaleBaseUtils.adapterDataFloat((float) trendHLvAdapter.getAvg(11,2)))+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1( trendHLvAdapter.getChange(11,2))+"":"";
                    title13=AppConfig.getInstance().isKgModel()?unitKg:unitLb;;
                    break;
            }

        }else if(current_GongNeng_rg_index==12){
            switch (current_GongNeng_rg_index){
                case 0:
                    title11=avg_weight_month;
                    title21=change_weight;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1(ScaleBaseUtils.adapterDataFloat( trendHLvAdapter.getAvg(11,0)))+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1( trendHLvAdapter.getChange(11,0))+"":"";
                    title13=AppConfig.getInstance().isKgModel()?unitKg:unitLb;
                    break;
                case 1:
                    title11=avg_bfp_month;
                    title21=change_bodyfat_percentage;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1(trendHLvAdapter.getAvg(11,1))+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1(trendHLvAdapter.getChange(11,1))+"":"";
                    title13="%";
                    break;
                case 2:
                    title11=avg_mass_month;
                    title21=change_muscle_mass;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1(ScaleBaseUtils.adapterDataFloat( trendHLvAdapter.getAvg(11,2)))+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei1(trendHLvAdapter.getChange(11,2))+"":"";
                    title13=AppConfig.getInstance().isKgModel()?unitKg:unitLb;
                    break;
            }

        }

        if (trend_avg_weight_cb1!=null){
            trend_avg_weight_cb1.setTitle1(title11);
            trend_avg_weight_cb1.setTitle2(title12);
            trend_avg_weight_cb1.setTitle3(title13);
        }
        if (trend_change_weight_cb1!=null){
            trend_change_weight_cb1.setTitle1(title21);
            trend_change_weight_cb1.setTitle2(title22);
            trend_change_weight_cb1.setTitle3(title13);
        }

    }



}
